package mq

import (
	"fmt"
	"log"

	"github.com/streadway/amqp"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
		fmt.Printf("%s: %s", msg, err)
	}
}

// SendMsgFromRabbit SendMsgFromRabbit
func SendMsgFromRabbit(msg string) {
	conn, err := amqp.Dial("amqp://rabbitmq:123456@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	// 声明交换路由
	exchangeName := "txcommon"
	err = ch.ExchangeDeclare(
		exchangeName,
		"fanout",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "Failed to declare an exchange")

	err = ch.Publish(
		exchangeName,
		"",
		false,
		false,
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(msg),
		})
	log.Println("send ok")
	fmt.Printf("send ok")
	failOnError(err, "Fail to publish a message")
}
